﻿@using LuckyFish.Blog.Models
@using Microsoft.EntityFrameworkCore
@inherits LayoutComponentBase
@layout MainLayout
@inject IDbContextFactory<BlogContext> DbFactory
@inject NavigationManager navigation
@inject AuthenticationStateProvider authStateProvider
@inject MessageService MessageService

<PageTitle>管理员界面</PageTitle>

<AuthorizeView>
    <Authorized>
        <h3>你好,@context.User.Identity!.Name</h3>
        @Body
    </Authorized>
    <Authorizing>
        <p>正在验证身份</p>
    </Authorizing>
    <NotAuthorized>
        <Row ItemsPerRow="ItemsPerRow.One">
            <Card IsShadow="true" IsCenter="true">
                <BodyTemplate>
                    <h2>登录</h2>
                    <ValidateForm OnValidSubmit="@Done" Model="@Model">
                        <Row ItemsPerRow="ItemsPerRow.One">
                            <FloatingLabel PlaceHolder="Name" DisplayText="账号" IsGroupBox="true" @bind-Value="@Model.Name" TValue="string"/>
                            <FloatingLabel PlaceHolder="Password" DisplayText="密码" IsGroupBox="true" TValue="string" @bind-Value="@Model.Password" type="password"/>
                            <Button style="width: 100%" 
                                    IsAsync="true" ButtonType="ButtonType.Submit" 
                                    Color="Color.Primary" Icon="oi oi-account-login" Text="登录"></Button>
                            <Divider/>
                        </Row>
                    </ValidateForm>
                </BodyTemplate>
            </Card>
        </Row>
    </NotAuthorized>
</AuthorizeView>

@code
{
    private AdminModel Model { get; set; } = new();

    private async Task Done(EditContext arg)
    {
        if (string.IsNullOrEmpty(Model.Name) || string.IsNullOrEmpty(Model.Password))
        {
            await MessageService.Show(new MessageOption() { Content = "没数据" });
            return;
        }

        await using var context = await DbFactory.CreateDbContextAsync();

        if (!await context.Admins.AnyAsync(x => x.Password == Model.Password && x.Name == Model.Name))
        {
            await MessageService.Show(new MessageOption() { Content = "账号密码出错" });
            return;
        }
        var provider = (Provider)authStateProvider;
        await provider.UpdateAuthState(Model);
        navigation.NavigateTo("/Admin", true);
    }
}